package org.lixf.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtils {

	private final static String URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8";
	private final static String USER = "root";
	private final static String PASSWORD = "root";
	
	private static Connection conn;
	
	static {
		try {
			// 1.加载驱动程序
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() throws SQLException {
		// 2.获得数据库的连接
		if (conn == null || conn.isClosed()) {
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		}
		return conn;
	}
	
	public static void close(Statement stmt, ResultSet rs) throws SQLException {
		if (conn != null && !conn.isClosed()) {
			conn.close();
		}
		if (stmt != null && !stmt.isClosed()) {
			stmt.close();
		}
		if (rs != null && !rs.isClosed()) {
			rs.close();
		}
	}
	
}
